// 活动视频渲染至 Canvas（抠像管线）:
import { useEffect } from "react";
import { processChromaKey } from "../gl";

interface UseActiveStreamRenderProps {
    activeStreamId: string;
    streams: Map<string, MediaStream>;
    videoRefs: React.MutableRefObject<Map<string, HTMLVideoElement>>;
    canvasRef: React.RefObject<HTMLCanvasElement | null>;
}

export default function useActiveStreamRender({
    activeStreamId,
    streams,
    videoRefs,
    canvasRef,
}: UseActiveStreamRenderProps) {
    useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas) return;

        // 静音所有非活动视频
        videoRefs.current.forEach((videoEl, id) => {
            videoEl.muted = id !== activeStreamId;
        });

        const activeVideo = videoRefs.current.get(activeStreamId);
        if (!activeVideo) return;

        const handleCanPlay = () => {
            if (activeVideo.paused) {
                activeVideo.play().catch((e) => console.error("切换时播放视频失败:", e));
            }
            processChromaKey(activeVideo, canvas);
        };

        if (activeVideo.readyState >= 3) {
            handleCanPlay();
        } else {
            activeVideo.addEventListener("canplay", handleCanPlay, { once: true });
        }

        return () => {
            activeVideo.removeEventListener("canplay", handleCanPlay);
        };
    }, [activeStreamId, streams, videoRefs, canvasRef]);
} 